import {
  Controller,
  Res,
  Get,
  Post,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { join } from 'path';

// 使用 文件流 下载文件、图片
import { zip } from 'compressing';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  // 可上传 图片、文件
  @Post('album')
  @UseInterceptors(FileInterceptor('file')) // 中间件(装饰器) 处理单个文件
  // 参数装饰器读取文件
  upload(@UploadedFile() file, @Res() res: Response) {
    const flag = Boolean(file);
    res.send({
      code: flag ? 0 : 1,
      msg: flag ? '上传成功' : '上传失败',
    });
  }

  // 使用 download 直接下载
  @Get('download')
  downloadImg(@Res() res: Response) {

    const url = join(__dirname, '../images/downloadImg.jpg');
    res.download(url);
  }

  // 使用 流 下载
  @Get('streamDlImg')
  async streamDownloadImg(@Res() res: Response) {
    const url = join(__dirname, '../images/downloadImg.jpg');
    const tarStream = new zip.Stream();
    await tarStream.addEntry(url);

    // 固定写法
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=customName.zip`,
    );

    tarStream.pipe(res);
  }
}
